package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import io.swagger.annotations.Api;
import com.itheima.health.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录校验
     * @param map 前端传递进来的用户输入的手机号和验证码
     * @param session 登录成功存入到session域中
     * @return 返回user
     */
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map map, HttpSession session) {

        // 获取用户手机号
        String telephone = map.get("telephone").toString();

        // 获取用户输入的验证码
        String validateCode = map.get("validateCode").toString();

        // 判断验证码是否舒服正确
        String code = redisTemplate.opsForValue().get(telephone).toString();
        if (code == null || !(code.equals(validateCode))) {

            // 进入到里面说明验证码不对,返回false
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        // 登录成功,去数据库查询是否是新用户
        Member member = memberService.smsLogin(telephone);

        // redis中删除验证码
        redisTemplate.delete(telephone);

        // 存到session域中
        session.setAttribute("user",member.getId());

        // 登录完成
        return new Result(true, MessageConst.LOGIN_SUCCESS);

    }
}
